﻿/*
 Copyright (c) 2011 Seth Juarez

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

using System;
using ml.Math;
using System.IO;
using ml.Supervised;
using ml.Tests.Model;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ml.Tests
{
    [TestClass]
    public class DecisionTreeTests
    {
        const string PATH = @"C:\MLTests";

        #region test factories

        private static Vector _getStaticRandom50Vector = null;

        //return a vector of random 50 used by a few tests
        private static Vector GetStaticRandom50Vector() 
        {
            if (_getStaticRandom50Vector == null) 
            {
                _getStaticRandom50Vector = Vector.Rand(50);
            }
            return _getStaticRandom50Vector;
        }

        private static Vector _getYVector = null;

        //return a vector used by Test_Continuous_Split
        private static Vector GetYVector() 
        {
            if (_getYVector == null) 
            {
                Vector xVector = GetStaticRandom50Vector();
                var seg = xVector.Segment(5);
                // set h(y|x) = 0
                _getYVector = Vector.Calc(xVector, d => {
                    int i = 1;
                    for (i = 1; i < seg.Length; i++)
                        if (d >= seg[i - i] && d < seg[i])
                            return (i % 2 == 0) ? 1 : -1;
                    return -1;
                });
            }
            return _getYVector;
        }

        #endregion test factories

        [TestInitialize]
        public void InitializeTest()
        {
            if (!Directory.Exists(@"C:\MLTests"))
                Directory.CreateDirectory(@"C:\MLTests");

            // we need to ensure the file exists before we 
            // call, so we will call Test_Decision_Tree_Save first
            Test_Decision_Tree_Save();
        }

        [TestMethod]
        public void Test_Vector_Mode()
        {
            Vector v = new[] { 1, 2, 1, 4, 2, 3, 5, 3, 1, 3, 1, 1, 1, 1, 1 };
            Assert.AreEqual(1, v.Mode());
        }

        [TestMethod]
        public void Test_Matrix_Vector_Removal()
        {
            Matrix m = new[,]
                {{ 1, 2, 3},
                 { 4, 5, 6},
                 { 7, 8, 9},
                 { 4, 9, 1}};

            Matrix col1 = new[,]
                            {{ 1, 3},
                             { 4, 6},
                             { 7, 9},
                             { 4, 1}};

            Matrix row1 = new[,]
                            {{ 1, 2, 3},
                             { 4, 5, 6},
                             { 4, 9, 1}};

            Assert.AreEqual(col1, m.Remove(1, VectorType.Column));
            Assert.AreEqual(row1, m.Remove(2, VectorType.Row));
            Assert.AreEqual(col1, m[v => v[0] != 2, VectorType.Column]);
            Assert.AreEqual(row1, m[v => v[0] != 7, VectorType.Row]);

            Assert.AreEqual(col1, m.Slice(m.Indices(v => v[0] != 2, VectorType.Column), VectorType.Column));
            Assert.AreEqual(row1, m.Slice(m.Indices(v => v[0] != 7, VectorType.Row), VectorType.Row));
        }

        [TestMethod]
        public void Test_Decision_Tree()
        {
            var data = Travel.GetData();

            // test point
            var s = new Travel() { Cars = 2, Cost = Cost.Expensive, Gender = Gender.Male, IncomeLevel = IncomeLevel.High };

            var model = new DecisionTreeModel<Travel>(3, type: ImpurityType.Entropy);
            var predictor = model.Generate(data);

            predictor.Predict(s);
        }

        [TestMethod]
        public void Test_Decision_Tree_Save()
        {
            string path = PATH + @"\decision_tree_serialize_test.xml";

            var data = Travel.GetData();

            var model = new DecisionTreeModel<Travel>(10, type: ImpurityType.Entropy);
            var predictor = model.Generate(data);
            predictor.Save(path);
        }

        [TestMethod, ExpectedException(typeof(InvalidOperationException))]
        public void Test_Decision_Tree_Invalid_Enum_Value()
        {
            var data = Travel.GetData();

            // test point
            var s = new Travel() { Cars = 2, Cost = Cost.Expensive, Gender = Gender.Male, IncomeLevel = IncomeLevel.High };

            var model = new DecisionTreeModel<Travel>(3, type: ImpurityType.Entropy);
            var predictor = model.Generate(data);

            s.Cost = (Cost)(-1.0);
            s.Gender = (Gender)(-1.0);
            s.IncomeLevel = (IncomeLevel)(-1.0);

            predictor.Predict(s);
        }

        [TestMethod]
        public void Test_Decision_Tree_Load()
        {
            string path = PATH + @"\decision_tree_serialize_test.xml";

            // test point
            var s = new Travel() { Cars = 2, Cost = Cost.Expensive, Gender = Gender.Male, IncomeLevel = IncomeLevel.High };

            var model = new DecisionTreeModel<Travel>();
            var predictor = model.Load(path);
            predictor.Predict(s);
        }

        [TestMethod]
        public void Test_GetStaticRandom50Vector_Has5OrMoreSegments() {
            Vector xVector = GetStaticRandom50Vector();
            Assert.IsTrue(xVector.Length >= 5);
        }

        [TestMethod]
        public void Test_Conditional_Entropy_Should_Be_Zero() {
            Vector xVector = GetStaticRandom50Vector();
         
            // set h(y|x) = 0
            Vector yVector = GetYVector();

            // conditional entropy should be 0!
            var h_yx = Entropy.Of(yVector).Given(xVector).Value;
            Assert.AreEqual<int>(0, (int)h_yx);
        }

        [TestMethod]
        public void Test_RelGain() 
        {
            Vector xVector = GetStaticRandom50Vector();
            // set h(y|x) = 0
            Vector yVector = GetYVector();

            // RelGain = (h(y) - h(y|x)) / h(y) = h(y) / h(y) = 1
            var s = Entropy.Of(yVector).Given(xVector).WithWidth(5).RelativeGain();
            Assert.AreEqual<int>(1, (int)s);
        }

        [TestMethod]
        public void Test_Continuous_Split()
        {
            Vector xVector = GetStaticRandom50Vector();
            var seg = xVector.Segment(5);
            // set h(y|x) = 0
            Vector yVector = GetYVector();

            // the last two assertions prove that feature 1
            // of the example matrix below is the BEST representation
            // that performs a perfect separation of the data
            Matrix xMatrix = Matrix.VStack(Vector.Range(50), xVector, Vector.Range(50, 100));

            var model = new DecisionTreeModel<Fake>(50, 5, ImpurityType.Entropy);
            // setting up fake setting
            model.X = xMatrix;
            model.Y = yVector;
            model.Description = Converter.GetDescription(typeof(Fake));

            // generate predictor and verify splits
            var pred = (DecisionTreePredictor<Fake>)model.Generate();
            for (int i = 1; i < seg.Length; i++)
                if (i % 2 == 0)
                    Assert.AreEqual<double>(1, pred.Tree.Children[i - 1].Label);
                else
                    Assert.AreEqual<double>(-1, pred.Tree.Children[i - 1].Label);

            // run predictions on all ranges
            for (int i = 0; i < seg.Length - 1; i++)
            {
                Fake test = new Fake { Feature1 = 2, Feature2 = seg[i], Feature3 = 51 };
                pred.Predict(test);
                Assert.AreEqual<bool>(i % 2 > 0, test.Label);
            }
        }
    }
}
